import React from "react";
import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd";
import WidgetOfBase from "../WidgetOfBase";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { Button, Table, Upload, Icon, Form, Input, Checkbox, Popover, Modal as ModalP } from 'antd';
import "./index.less";
import XLSX from "xlsx";
import { Resizable } from 'react-resizable';
// import 'react-resizable/css/styles.css';
import ExportJsonExcel from "js-export-excel";
import moment from "moment";

// import EditableCell from './editableCell';
const CheckboxGroup = Checkbox.Group;
const EditableContext = React.createContext();

const ResizeableTitle = (props) => {
    const { onResize, width, onClick, ...restProps } = props;
    let resizing = false;
    if (!width) {
        return <th {...restProps} />
    }
    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            onResizeStart={() => { resizing = true; }}
            onResizeStop={() => {
                resizing = true;
                setTimeout(() => {
                    resizing = false;
                }, 100);
            }}
            draggableOpts={{ enableUserSelectHack: false }}
        >
            <th {...restProps}
                onClick={(...args) => {
                    if (!resizing && onClick) {
                        onClick(...args);
                    }
                }}
            />
        </ Resizable >
    )
};

const getItemStyle = (isDragging, draggableStyle) => ({
    // // some basic styles to make the items look a bit nicer
    // userSelect: "none",
    display: 'flex',
    justifyContent: 'space-between',
    // change background colour if dragging
    background: isDragging ? "#fff" : "#fff",
    // styles we need to apply on draggables
    ...draggableStyle
});

const getListStyle = isDraggingOver => ({
    background: isDraggingOver ? "lightblue" : "#fff",
    display: 'flex',
    flexDirection: 'column'
});

const reorder = (list, startIndex, endIndex) => {
    const result = Array.from(list);
    const [removed] = result.splice(startIndex, 1);
    result.splice(endIndex, 0, removed);

    return result;
};

const EditableRow = ({ form, index, ...props }) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);
class EditableCell extends React.Component {
    state = {
        editing: false,
    };

    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({ editing }, () => {
            if (editing && this.input) {
                this.input.focus();
            }
        });
    };

    save = e => {
        const { record, onTableCellhandleSave, inputtype } = this.props;
        this.form.validateFields((error, values) => {
            if (inputtype === 'number' && (values[e.currentTarget.id] !== undefined)) {
                values[e.currentTarget.id] = +values[e.currentTarget.id];
            }
            if (error && error[e.currentTarget.id]) {
                return;
            }
            this.toggleEdit();

            onTableCellhandleSave(record, e.currentTarget.id, { ...values });
        });
    };

    getInput = () => {
        const { inputtype, title } = this.props;
        if (inputtype === 'number' || inputtype === 'text') {
            return <Input size="small"
                ref={node => (this.input = node)}
                type={inputtype}
                onPressEnter={this.save}
                onBlur={this.save}
            />
        }
        return <span>{title}</span>
    };

    renderCell = form => {
        this.form = form;
        const { children, dataIndex, inputtype, record } = this.props;
        const { editing } = this.state;
        return editing ? (
            <Form.Item style={{
                margin: 0,
                display: "inline-block",
                verticalAlign: 'middle',
                width: '100%'
            }}>
                {form.getFieldDecorator(dataIndex, {
                    // rules: [
                    //     {
                    //         required: true,
                    //         message: `${title} is required.`,
                    //     },
                    // ],
                    // initialValue: record[dataIndex],
                    initialValue: record.meta && record.meta[dataIndex] ? record.meta[dataIndex] : record[dataIndex],
                })(this.getInput())}
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{ paddingRight: 24 }}

            >
                {children}
                {(inputtype === 'number' || inputtype === 'text') && <Icon className="icon_edit" type="edit" onClick={this.toggleEdit} />}
            </div>
        );
    };

    render() {
        const {
            editable,
            dataIndex,
            title,
            record,
            index,
            onTableCellhandleSave,
            children,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editable ? (
                    <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
                ) : (
                    children
                )}
            </td>
        );
    }
}
class ReactTable extends WidgetOfBase {
    constructor(props) {
        super(props);
        // this.state.columns = (props.rcColumns || []);
        // this.state.dataSource = (props.dataSource || []);
        this.state.columns = [];
        this.state.dataSource = [];

        this.state.indeterminate = false;

        this.state.leftColumns = this.state.columns.filter(column => column?.fixed === 'left');
        this.state.centerColumns = this.state.columns.filter(column => (column?.fixed === undefined));
        this.state.rightColumns = this.state.columns.filter(column => column?.fixed === 'right');

        this.state.selectedRowKeys = [];
        this.state.searchValue = '';
        this.exportDataSource = [];
    };

    components = {
        header: {
            cell: ResizeableTitle,
        },
        body: {
            row: EditableFormRow,
            cell: EditableCell,
        }
    };

    handleResize = index => (e, { size }) => {
        const { tableSettingKey } = this.props;

        this.setState(({ columns }) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };

            if (tableSettingKey) {
                const localItems = nextColumns.map(column => {
                    return {
                        key: column.key,
                        show: column?.show,
                        fixed: column?.fixed || undefined,
                        width: column?.width,
                        index: column?.index
                    }
                })
                localStorage.setItem(tableSettingKey, JSON.stringify(localItems))
            }

            return { columns: nextColumns };
        });
    };

    onFileChange = (e) => {
        const { tableOnImportItems } = this.props;
        const file = e.file;
        let reader = new FileReader();
        reader.onload = (e) => {
            let data = e.target.result;
            let workbook = XLSX.read(data, { type: 'binary' });
            if (tableOnImportItems) {
                tableOnImportItems(workbook);
            }
        };
        reader.readAsBinaryString(file);
    };

    onExportTable = () => {
        const { tablePageTitle } = this.props;
        const { columns, dataSource } = this.state;

        let dataItems = [];
        for (let i = 0; i < dataSource.length; i++) {
            let item = {
                ...dataSource[i].meta,
                created: moment(dataSource[i].created).format('YYYY-MM-DD HH-MM-SS'),
                lastModified: moment(dataSource[i].lastModified).format('YYYY-MM-DD HH-MM-SS'),
            }
            dataItems.push(item);
        }

        let newColumns = columns.filter(column => (column?.show || column?.show === undefined)).sort((a, b) => {
            return this.compare(a, b);
        })
        let sheetFilter = newColumns.map(column => { return column.key })
        let sheetHeader = newColumns.map(column => { return column.title })
        let columnWidths = newColumns.map(column => { return ((column?.width || 100) / 8) })
        this.exportCurrentExcel((tablePageTitle || '导出的Table'), dataItems, sheetFilter, sheetHeader, columnWidths)
    };

    exportItemsOnTable = (selectedRowKeys, callback) => {
        const { tablePageTitle } = this.props;
        const { columns } = this.state;

        let exportDataSource = selectedRowKeys.map((rowKeyItem)=>{
            for(let i = 0;i < this.exportDataSource?.length;i++){
                let item = this.exportDataSource[i];
                if(rowKeyItem === item.dataId){
                    return item;
                }
            }
            return null;
        });

        exportDataSource = exportDataSource.filter((item)=>{
            if(!item){
                return false
            } else {
                return true
            }
        })

        let dataItems = [];
        for (let i = 0; i < exportDataSource.length; i++) {
            let item = {
                ...exportDataSource[i].meta,
                created: moment(exportDataSource[i].created).format('YYYY-MM-DD HH-MM-SS'),
                lastModified: moment(exportDataSource[i].lastModified).format('YYYY-MM-DD HH-MM-SS'),
            }
            dataItems.push(item);
        }

        let newColumns = columns.filter(column => (column?.show || column?.show === undefined)).sort((a, b) => {
            return this.compare(a, b);
        })
        let sheetFilter = newColumns.map(column => { return column.key })
        let sheetHeader = newColumns.map(column => { return column.title })
        let columnWidths = newColumns.map(column => { return ((column?.width || 100) / 8) })
        this.exportCurrentExcel((tablePageTitle || '导出的Table'), dataItems, sheetFilter, sheetHeader, columnWidths)
    };

    exportCurrentExcel = (fileName, dataItems, sheetFilter, sheetHeader, columnWidths) => {
        let option = {};
        option.fileName = fileName;
        option.datas = [
            {
                sheetData: dataItems,
                sheetName: fileName,
                sheetFilter: sheetFilter,
                sheetHeader: sheetHeader,
                columnWidths: columnWidths
            }
        ];
        var toExcel = new ExportJsonExcel(option); //new
        toExcel.saveExcel(); //保存
    };

    onChangeCheckGroup = (checkedList) => {
        let newColumns = this.state.columns.map(column => {
            if (checkedList.indexOf(column.key) > -1) {
                column.show = true;
            } else {
                column.show = false;
            }
            return column;
        })
        this.updateAndSaveTheLocal(newColumns);
        this.setState({
            indeterminate: !!checkedList.length && checkedList.length < this.state.columns.length,
        })
    };

    onCheckAllChange = checked => {
        const newColumns = this.state.columns.map(column => {
            if (checked) {
                column.show = true;
            } else {
                column.show = false;
            }
            return column
        })
        this.updateAndSaveTheLocal(newColumns);
        this.setState({
            indeterminate: false,
        });
    };

    createPopoverTitle = () => {
        const checkedShow = this.state.columns.filter(column => (column?.show || column?.show === undefined))
        return (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Checkbox
                    indeterminate={this.state.indeterminate}
                    onChange={(e) => this.onCheckAllChange(e.target.checked)}
                    checked={this.state.columns.length <= checkedShow.length}
                >列展示</Checkbox>
                <Button style={{ paddingRight: '0' }} onClick={() => { this.onCheckAllChange(true) }} type="link">重置</Button>
            </div>
        )
    };

    onDragStart = () => {
        // good times
        if (window.navigator.vibrate) {
            window.navigator.vibrate(100);
        }
    };

    onDragEnd = (result) => {
        if (!result.destination) {
            return;
        }

        const { columns } = this.state;
        let leftColumns = columns.filter(column => column?.fixed === 'left').sort((a, b) => {
            return this.compare(a, b);
        });
        let centerColumns = columns.filter(column => column?.fixed === undefined).sort((a, b) => {
            return this.compare(a, b);
        });
        let rightColumns = columns.filter(column => column?.fixed === 'right').sort((a, b) => {
            return this.compare(a, b);
        });

        if (result.type === "left") {
            leftColumns = reorder(
                leftColumns,
                result.source.index,
                result.destination.index
            );

        } else if (result.type === "right") {
            rightColumns = reorder(
                rightColumns,
                result.source.index,
                result.destination.index
            );
        } else {
            centerColumns = reorder(
                centerColumns,
                result.source.index,
                result.destination.index
            );
        }

        this.updateAndSaveTheLocal(leftColumns.concat(centerColumns).concat(rightColumns));
    };

    updateAndSaveTheLocal = (columns) => {
        const sortColumns = columns.sort((a, b) => {
            if (a.show && !b.show) {
                return -1;
            }
            if (!a.show && b.show) {
                return 1;
            }
            return 0;
        })

        const { tableSettingKey } = this.props;

        if (tableSettingKey) {
            const localItems = sortColumns.map((column, index) => {
                return {
                    key: column.key,
                    show: column?.show,
                    fixed: column?.fixed || undefined,
                    width: column?.width || 100,
                    index: index
                }
            })
            localStorage.setItem(tableSettingKey, JSON.stringify(localItems))
        }
        const newColumns = sortColumns.map((column, index) => {
            return {
                ...column,
                index: index
            }
        })
        this.setState({
            columns: newColumns
        })
    };

    fixedColumn = (key, location) => {
        const index = this.state.columns.findIndex(column => column.key === key);
        if (index > -1) {
            this.state.columns[index]['fixed'] = location;
        }
        let leftColumns = this.state.columns.filter(column => column?.fixed === 'left');
        let centerColumns = this.state.columns.filter(column => column?.fixed === undefined);
        let rightColumns = this.state.columns.filter(column => column?.fixed === 'right');
        this.updateAndSaveTheLocal(leftColumns.concat(centerColumns).concat(rightColumns));
    };

    setColumns = (ngWidth) => {
        const { tableSettingKey, minWidth } = this.props;
        const lastItem = localStorage.getItem(tableSettingKey);
        const lastItemRes = lastItem && JSON.parse(lastItem);
        for (let i = 0; i < this.state.columns.length; i++) {
            let column = this.state.columns[i];
            if (lastItemRes) {
                const indexKey = lastItemRes.findIndex(i => (i.key === column.key));
                if (indexKey > -1) {
                    column.width = lastItemRes[indexKey].width;
                    column.fixed = lastItemRes[indexKey].fixed;
                    column.show = lastItemRes[indexKey].show;
                    column.index = lastItemRes[indexKey].index;
                }
            } else if (ngWidth) {
                const width = minWidth ? (ngWidth > minWidth ? ngWidth : minWidth) : ngWidth;
                column.width = width;
            }
        }
        const sortColumns = this.state.columns.sort((a, b) => {
            if (a.show && !b.show) {
                return -1;
            }
            if (!a.show && b.show) {
                return 1;
            }
            return 0;
        })
        this.setState({
            columns: [...sortColumns]
        })
    }

    // componentWillMount = () => {
    //     this.setColumns();
    //     // this.updateAndSaveTheLocal(this.state.columns)
    // };

    componentDidMount = () => {
        this.props.onRef(this);
        this.onUpdateColums();
    };

    onUpdateColums = () => {
        const { tableSettingKey } = this.props;
        const lastItem = localStorage.getItem(tableSettingKey);
        const lastItemRes = lastItem && JSON.parse(lastItem);
        const wrapDom = document.getElementsByClassName('multifun_table');
        if (wrapDom?.length && wrapDom[0]?.offsetWidth && !lastItemRes) {
            const width = (wrapDom[0]?.offsetWidth) / (this.state.columns.length);
            this.setColumns(width);
        } else {
            this.setColumns();
        }
    };

    // componentDidUpdate = () => {
    //     console.log('ngtable componentDidUpdate')
    //     this.onUpdateColums();
    // };

    componentWillReceiveProps(nextProps) {
        if ((nextProps.rcColumns.length !== this.state.columns.length) || (nextProps.dataSource.length !== this.state.dataSource.length)) {
            this.setState({
                dataSource: nextProps.dataSource,
                columns: nextProps.rcColumns
            }, () => {
                this.onUpdateColums();
            })
        }
    };

    createCheckboxGroup = (columns, title) => {
        const txt = title === 'left' ? '固定在左侧' : title === 'right' ? '固定在右侧' : '不固定';
        if (columns?.length > 0) {
            return (
                <div>
                    {
                        txt && (<div> {txt} </div>)
                    }
                    <div >
                        <DragDropContext
                            onDragStart={this.onDragStart}
                            onDragEnd={(result) => this.onDragEnd(result, columns)}
                        >
                            <Droppable
                                droppableId="board"
                                type={title}
                                direction="vertical"
                            >
                                {(provided, snapshot) => (
                                    <div
                                        {...provided.droppableProps}
                                        ref={provided.innerRef}
                                        style={getListStyle(snapshot.isDraggingOver)}
                                    >
                                        {columns.map((column, index) => (
                                            <Draggable
                                                key={column.key}
                                                draggableId={column.key}
                                                index={index}>
                                                {(provided, snapshot) => (
                                                    <div
                                                        ref={provided.innerRef}
                                                        {...provided.draggableProps}
                                                        {...provided.dragHandleProps}
                                                        style={getItemStyle(
                                                            snapshot.isDragging,
                                                            provided.draggableProps.style
                                                        )}
                                                    >
                                                        <div className="multitable_columnList">
                                                            <Checkbox
                                                                value={column.key}
                                                            >{column.title}</Checkbox>
                                                            {/* <div className="columnfix_icon">
                                                                {
                                                                    (title === 'left' || title === 'right') && (<Tooltip title="不固定">
                                                                        <Icon type="vertical-align-middle"
                                                                            onClick={() => { this.fixedColumn(column.key) }}
                                                                        />
                                                                    </Tooltip>)
                                                                }
                                                                {
                                                                    title !== 'left' && (
                                                                        <Tooltip title="固定在列首">
                                                                            <Icon
                                                                                type="vertical-align-top"
                                                                                onClick={() => { this.fixedColumn(column.key, 'left') }}
                                                                            />
                                                                        </Tooltip>
                                                                    )
                                                                }
                                                                {
                                                                    title !== 'right' && (
                                                                        <Tooltip title="固定在列尾">
                                                                            <Icon type="vertical-align-bottom"
                                                                                onClick={() => { this.fixedColumn(column.key, 'right') }}
                                                                            />
                                                                        </Tooltip>
                                                                    )
                                                                }
                                                            </div> */}
                                                        </div>
                                                    </div>
                                                )}
                                            </Draggable>
                                        ))}
                                        {provided.placeholder}
                                    </div>
                                )}
                            </Droppable>
                        </DragDropContext>
                    </div>
                </div >
            )
        } else {
            return null;
        }
    };

    createPopoverContent = () => {
        const { columns } = this.state;
        let leftColumns = columns.filter(column => column?.fixed === 'left').sort((a, b) => {
            return this.compare(a, b);
        });
        let centerColumns = columns.filter(column => (column?.fixed === undefined)).sort((a, b) => {
            return this.compare(a, b);
        });
        let rightColumns = columns.filter(column => column?.fixed === 'right').sort((a, b) => {
            return this.compare(a, b);
        });
        const hasCheckedKeys = (columns.filter(column => (column?.show || (column?.show === undefined)))).map(columnKey => { return columnKey.key })
        return (
            <div className="table_popovercontent">
                <CheckboxGroup
                    style={{ width: '100%' }}
                    value={hasCheckedKeys}
                    onChange={this.onChangeCheckGroup}
                >
                    {this.createCheckboxGroup(leftColumns, 'left')}
                    {this.createCheckboxGroup(centerColumns, 'center')}
                    {this.createCheckboxGroup(rightColumns, 'right')}
                </CheckboxGroup>
            </div>
        )
    };

    compare = (a, b) => {
        if (a.show && !b.show) {
            return -1;
        }
        if (!a.show && b.show) {
            return 1;
        }

        if (a.index > b.index) {
            return 1;
        }
        if (a.index < b.index) {
            return -1;
        }
        return 0;
    };

    onTableCellhandleSave = (record, cellId, params) => {
        const { tableOnChangeOneItem, onTableCellhandleSave0 } = this.props;
        if (onTableCellhandleSave0) {
            onTableCellhandleSave0(record, cellId, params, this.state.dataSource);
            return true;
        }

        let dataId = record?.dataId || record?.key;
        let needChange = false;
        const newData = [...this.state.dataSource];
        const index = newData.findIndex(item => item.key === dataId);
        const item = newData[index];
        const keys = Object.keys(params);
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            const value = params[key];
            if ((item.meta && item.meta[key] !== value) || item[key] !== value) {
                needChange = true;
            }
        }

        if (dataId && params && needChange) {
            tableOnChangeOneItem(dataId, params, changeRes => {
                if (changeRes) {
                    for (let i = 0; i < keys.length; i++) {
                        const key = keys[i];
                        const value = params[key];
                        if (item[key]) {
                            item[key] = value;
                        } else {
                            item.meta[key] = value;
                        }
                    }
                    newData.splice(index, 1, {
                        ...item
                    });
                    this.setState({ dataSource: newData });
                }
            });
        }
    };

    createTableOfHeader = () => {
        const { needCreateDelete, tableOnDeleteItems, tableTemplateLink, tableOnImportItems, tableImportBtnTxt, tableExportBtnTxt, onSearchTable, headLeftCustomButtons, headRightCustomButtons } = this.props;
        const { selectedRowKeys, searchValue } = this.state;
        return (
            <div className="multi_tablehead">
                <div className="multi_tableheadleft">
                    {
                        headLeftCustomButtons?.map(btn => {
                            return (
                                <Button
                                    className="headleft_item"
                                    disabled={btn?.disabled}
                                    size="small"
                                    onClick={() => {
                                        if (!btn.onClickBtn) {
                                            alert('need onClickBtn')
                                        } else {
                                            btn.onClickBtn()
                                        }
                                    }}>
                                    {btn.text}
                                </Button>
                            )
                        })
                    }
                    {
                        onSearchTable && (
                            <Input.Search className="headleft_item"
                                value={searchValue}
                                // disabled={!searchValue}
                                size="small"
                                onChange={(e) => {
                                    this.setState({
                                        searchValue: e.target.value
                                    })
                                }}
                                allowClear
                                onSearch={onSearchTable}
                                enterButton="搜索" />
                        )
                    }
                    {
                        tableImportBtnTxt && tableOnImportItems && (<React.Fragment>
                            <Upload
                                className="headleft_item"
                                onChange={(e) => {
                                    this.onFileChange(e);
                                }}
                                beforeUpload={() => false}
                                accept={'.xls, .xlsx'}
                            >
                                <Button
                                    size="small"
                                >
                                    <Icon type="download" />{tableImportBtnTxt}
                                </Button>
                            </Upload>

                        </React.Fragment>)
                    }
                    {
                        tableExportBtnTxt && (<Button
                            className="headleft_item"
                            size="small"
                            onClick={() => {
                                const _this = this;
                                ModalP.confirm({
                                    title: '是否进行导出EXCEL操作?',
                                    content: '当前页面展示的列，将会被导出',
                                    icon: <ExclamationCircleOutlined />,
                                    style: { display: 'flex', justifyContent: 'center' },
                                    okText: '是的，确定',
                                    okType: 'danger',
                                    cancelText: '不，再想想',
                                    onOk() {
                                        _this.onExportTable();
                                    },
                                    onCancel() {
                                    },
                                });
                            }}>
                            <Icon type="upload" />{tableExportBtnTxt}
                        </Button>)
                    }
                    {
                        tableTemplateLink && (<Button
                            size="small"
                            className="headleft_item"
                            type="link"
                            href={tableTemplateLink}
                            download={'test.jpeg'}
                            target={'_BLANK'}
                        >点击下载导入数据模板</Button>
                        )
                    }
                </div>
                <div className="multi_tableheadright">
                    {
                        tableExportBtnTxt && (
                            <Button
                                size="small"
                                className="headright_item"
                                disabled={selectedRowKeys.length <= 0}
                                onClick={() => {
                                    const _this = this;
                                    ModalP.confirm({
                                        title: '是否进行批量操作?',
                                        content: '当前选中的项，将会被导出',
                                        icon: <ExclamationCircleOutlined />,
                                        style: { display: 'flex', justifyContent: 'center' },
                                        okText: '是的，确定',
                                        okType: 'danger',
                                        cancelText: '不，再想想',
                                        onOk() {
                                            _this.exportItemsOnTable(selectedRowKeys, res => {
                                                if (res) {
                                                    _this.setState({
                                                        selectedRowKeys: []
                                                    })
                                                }
                                            });
                                        },
                                        onCancel() {
                                        },
                                    });

                                }}
                            >
                                批量{tableExportBtnTxt}
                            </Button>
                        )
                    }
                    {
                        needCreateDelete && (
                            <Button
                                size="small"
                                className="headright_item"
                                disabled={selectedRowKeys.length <= 0}
                                onClick={() => {
                                    const _this = this;
                                    ModalP.confirm({
                                        title: '是否进行批量操作?',
                                        icon: <ExclamationCircleOutlined />,
                                        style: { display: 'flex', justifyContent: 'center' },
                                        okText: '是的，确定',
                                        okType: 'danger',
                                        cancelText: '不，再想想',
                                        onOk() {
                                            tableOnDeleteItems(selectedRowKeys, res => {
                                                if (res) {
                                                    _this.setState({
                                                        selectedRowKeys: []
                                                    })
                                                }
                                            });
                                        },
                                        onCancel() {
                                        },
                                    });

                                }}
                            >
                                批量删除
                            </Button>
                        )
                    }
                    {
                        headRightCustomButtons?.map(btn => {
                            return (
                                <Button
                                    className="headright_item"
                                    size="small"
                                    disabled={btn?.disabled}
                                    onClick={() => {
                                        if (!btn.onClickBtn) {
                                            alert('need onClickBtn')
                                        } else {
                                            btn.onClickBtn()
                                        }
                                    }}>
                                    {btn.text}
                                </Button>
                            )
                        })
                    }
                    <Popover
                        placement="bottomRight"
                        title={this.createPopoverTitle()}
                        content={this.createPopoverContent()}
                        trigger="click"
                    >
                        <Button
                            className="headright_item"
                            size="small"
                            type="link">
                            <Icon type="setting" style={{ fontSize: '16px' }} />
                        </Button>
                    </Popover>
                </div>
            </div>
        )
    };

    renderOnMobile = () => {
        const { pagination, needCreateEditor, combinedData, needrowSelection, onChangeSelectedRow } = this.props;
        const { selectedRowKeys, dataSource } = this.state;
        let columns = (this.state.columns.filter(column => (column?.show || column?.show === undefined)))
            .sort((a, b) => {
                return this.compare(a, b);
            })
        columns = columns.map((col, index) => {
            if (!col.editable || !needCreateEditor) {
                return {
                    ...col,
                    onHeaderCell: (column) => ({
                        width: column.width,
                        onResize: this.handleResize(index),
                    })
                };
            }

            return {
                ...col,
                onHeaderCell: (column) => ({
                    width: column.width,
                    onResize: this.handleResize(index),
                }),
                onCell: record => ({
                    record,
                    editable: col.editable,
                    inputtype: col.type,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    onTableCellhandleSave: this.onTableCellhandleSave
                }),
            }
        });

        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys) => {
                for(let i = 0;i < selectedRowKeys?.length;i++){
                    let rowKeyItem = selectedRowKeys[i];
                    let findIndex = this.exportDataSource.findIndex((exportItem)=>{
                        return exportItem.dataId === rowKeyItem
                    });
                    if(findIndex === -1){
                        for(let j = 0;j < dataSource?.length;j++){
                            let dataItem = dataSource[j];
                            if(rowKeyItem === dataItem.dataId){
                                this.exportDataSource.push(dataItem);
                                break;
                            }
                        }
                    }
                }
                
                onChangeSelectedRow && onChangeSelectedRow(selectedRowKeys);
                this.setState({ selectedRowKeys })
            },
        };

        const footerColums = [{
            align: "center",
            dataIndex: "combined",
            key: "combined",
            title: "合计",
            type: "text",
            width: 60
        }].concat(columns);

        let footerDataSource = {
            combined: '合计'
        }

        const isHasCombined = ((JSON.stringify(combinedData) === "{}") || !combinedData || !dataSource?.length);
        if (!isHasCombined) {
            for (let key in combinedData) {
                footerDataSource[key] = combinedData[key];
            }
        }

        return (
            <div className="multifun_table" >
                <EditableContext.Provider value={this.props.form}>
                    <Table
                        columns={columns}
                        rowKey={(record) => {
                            const key = record?.dataId || record?.key;
                            return key;
                        }}
                        components={this.components}
                        dataSource={dataSource}
                        pagination={pagination}
                        size="small"
                        rowClassName={() => 'editable-row'}
                        rowSelection={needrowSelection ? rowSelection : null}
                        scroll={{ x: dataSource.length > 0 ? 50 : '100%' }}
                        style={{ padding: '10px' }}
                        bodyStyle={{ fontSize: '13px' }}
                        title={() => this.createTableOfHeader()}
                        footer={() => {
                            if (!isHasCombined) {
                                return (
                                    <Table
                                        columns={footerColums}
                                        rowKey={(record) => {
                                            return record;
                                        }}
                                        dataSource={dataSource.length > 0 ? [footerDataSource] : []}
                                        size="small"
                                        showHeader={false}
                                        pagination={false}
                                        scroll={{ x: dataSource.length > 0 ? 50 : '100%' }}
                                        bodyStyle={{ fontSize: '13px' }}
                                    />
                                )
                            } else {
                                return null;
                            }
                        }}
                    />
                </EditableContext.Provider>
            </div>
        )
    }
}

const NGTable = Form.create()(ReactTable);

export default NGTable;
